JavaScript Vital Few Notes

Introduction Working with Strings Timer Methods JavaScript with HTML5 Creating Objects in JavaScript
Syntax Working with Date Object Working with Forms JavaScript and HTML5 Video Handling Errors
Script Locations DOM Scripting Styling Elements Web Workers Misc.
Functions and Events Changing DOM Elements Animating Objects Feature Detection  
Debugging Errors Event and EventListeners JavaScript Best Practices Using Modernizr  

Vital Few

Javascript:

  1. is typically uses as a light weight client side programming language of the Web based on the ECMAScript standard that add interactivity to a web page. It is THE scripting language of the web. JavaScript can also be used as a server-side language (i.e., node.js at http://www.nodejs.org). Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
  2. works inside a browser that have a built-in JavaScript engine.
  3. can be written as plain text with a text editor or any other tools (i.e., Dreamweaver) that support text files.
  4. is a case sensitive and a weakly type language which means that you can place whatever value you want into the variable and change it to another data type at any time.
  5. is an interpret language while means that it is not compiled like a program but rather "interpreted" by a JavaScript interpreter built into the browser. The drawback to compiling is that if a change needs to be made the file has to be compiled again.
  6. can not access the user files / directories, database or hardware (i.e., USB drive).
  7. is used to add functionality, validate forms, communicate with the server, add interactivity to HTML pages, add cookies, detect visitor browser, etc.
  8. is typically embedded within HTML pages or linked from an external file.
  9. can be used without a license.
  10. is NOT Java. Java developed by Sun Microsystems is a powerful and much more complex programming language - in the same category as C and C++.
  11. can react to events. A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element.
  12. can read and write HTML elements. A JavaScript can read and change the content of an HTML element
  13. can be used to add or remove CSS style from a HTML page or change CSS properties to create animation or interactivity based on user input of mouse event.
  14. can be used to communicate with a server via AJAX to retrieve or update information without having to load a new web page. AJAX has placed JavaScript back on the radar.
  15. is an object oriented programming language but does not use classes like other programming languages becasue it is prototype based and not class based.
  16. is not a typed language like other programming languages so it does NOT define different types of numbers.
  17. all numbers are stored as 64-bit (8 bytes) base 10 floating point numbers.
  18. interprets numeric constants as octal if preceded by a zero (0123), and as hexadecimal if preceded by a 0x (0xFFF). As a result, you should never write a number with a leading zero unless you want an octal conversion.


IMPORTANT NOTE: Instead of using alert(...) to trace the result of a variable, we will be using console.log(....) using Firefox Firebug plugin. You can also trace multiple variables by separating them by commas (i.e., console.log(var1, var2, var3). The Firebug console needs to be open to see traces.

[Back to Top]

Syntax

JavaScript is case sensitive for its key words; however, it is whitespace insensitive (i.e., line return, etc.) between key words. Note spaces are important when it is in a string (i.e., "First              Name").

Flash and JS: JavaScript statement should end with a semicolon (;) so that you can place multiple statements on the same line. However this is not best practice. It is best to have each statements on it own line even if that statement wraps to multiple lines.

Flash and JS: Single line comments (//) should be added on the line above or to the right of a statement but not to the left of a statement. Block level comments start with "/*" and ends with "*/" on used with multiple lines.

The type attribute is not used with HTML 5 when writing the <script> tags (i.e, <script src="myscript.js" type="text/javascript></script>) is now (<script src="myscript.js"></script>)

Flash and JS: JavaScript syntax is similar to Flash ActionScript syntax with a few exceptions that will be noted. (See Programming Constructs for details).

[Back to Top]

Script Locations

JavaScript <script> tags can be placed anywhere in an HTML file. However, because the browser reads code from the top to the bottom, where it is placed is important to how and when the code is executed.

1. BETWEEN the <head> tag

If you want the script to execute automatically when a page loads (unless you place the script within a function) you can place it between the <head> tags.

Like CSS, you can have the script embedded in the <head> tag using the <script> tag similar to the <style> tag that is used for embedded CSS.

<script>
alert("Script has been executed.")
</scrpt>

NOTE: The alert dialog box will be displayed because it is in the <head> tag and execute FIRST.  However, the page itself is NOT display because the alert dialogbox has suspended the code until the OK button is clicked. The alert box will appear BEFORE the page is displayed. To see the page, the OK button has to be clicked.

You can also link JavaScript to an external JavaScript file (*.js) with the <script> tag and a src attribute like an <img> or <a> tag. It is important to note that there is no text between the <script></script> tags pair.

<script src="myscript.js"></script>

Like an external CSS file, external scripts are best used when the code is shared among many pages. This makes it easier to update the code in one place for all of the associated pages.

It is best practice to place script in an external *.js file so that you separate the presentation layer from the behavior layer. It also makes the code easier to maintain. To move an embedded (internal) script to a external file, cut the content from between the <script> tags and paste it into an external *.js file. Then, in the HTML page, add a src attribute to refer back to that file with the same <script> tags (i.e., <script src="myscript.js"></script>.) Note: External script does not include the <script></script> tags-- only the code within the <script> tag.

If you place a script in the head that calls an object that does not yet exist because the script is in the head, the code will not work. To avoid this problem it is best practice to use the following syntax to ensure the the whole page load BEFORE the main code runs: (CODE BELOW IS NOT WORKING)

window.load = function ()
{
mainFunction();
}

mainFunction()
    {
    var myImage = getElementById("myImage");
    myImage.click = function()
   {
    alert("This is a test");
    }
}

NOTE: The window.load should only be used once per page.

2. IN the <body> tag

If you want to "write" to a page dynamically, you can place a <script> tag within the <body> tag.

<body>
...
<script>
document.write ("Hello, world")
</scrpt>

...
</body>

CAUTION:  Avoid using document.write() in real world JavaScript code as the entire HTML page will be overwritten if used inside a function, or after the page is loaded. However, document.write() is an easy way to demonstrate JavaScript. Instead use the innerHTML method to write to an existing tag:

<script>
document.getElementById("currentTime").innerHTML=Date();
</script>

<p id="currentTime"></p>

3. AFTER the closing </body> tag

You can place the <script> tag AFTER the closing </body> tag when you want the page to load first before the script is executed.

NOTES:


To get all of a given element on a page use the getElementByTagName method to ascertain how many element of that type exist on the page. For example,

var totalLinkOnPage = document.getElementByTagName("a")

This will return an array of the elements on the page. This will work for any page element.

[Back to Top]

Functions and Events

JavaScript in an HTML page will be executed when the page loads which may not be what is needed. To execute a JavaScript when an event occurs, such as a mouse click, the script can be placed IN a function.
Events are normally used in combination with functions (like calling a function when an event occurs). A function can be called from anywhere within a page or from another page if it is link to an external file. However, it is best practice to place functions in the <head> if they are not in an external file to ensure the function is read by the browser before it is called.

<html>
<head>
<script>
function show_msg()
{
   alert("Hello, World!");
}
</script>
</head>
<body>
<input type="button" onclick="show_msg()" value="Show Message" />
</body>
</html>

[Back to Top]

Debugging Errors

If there are errors in the code, the browser usually does not give any indication of them. To "see" errors (or warnings), a variety of error consoles can be used depending on the browser type.

Firefox JavaScript Console - Web Developer>Error Console (Displays JavaScript and CSS errors.) The Firebug plug-in (http://getfirebug.com/) greatly expands the functionality of the Forefox's Error Console.

Internet Explorer 9 - F12 (Displays JavaScript, and analyze CSS and HTM) Unlike FF which keeps a running total of errors, with IE you have to open the Error Console then reoloard the page to see an error.

Chrome JavaScript Console - Click on the tools icon and select the Tools menu and select JavaScript console.

Safari JavaScript Console - Developer>Show Error Console. Choose Safari>Preferences and then choose the Advanced button and check the "Show Develop menu in the menu bar" and close the Preferences window. Then, restart Safari to see menu.

[Back to Top]

Working with Strings

Flash and JS: When creating a string with multiple quotes, it may not be enough to use both double and single quotes. You may still need to escape quotes in the strings. For example:

var multipleQuotes = "He said,"she's cute" and then smile at her."

Single quotes and double quotes will not work because the single quote in the "she's" still needs to be escaped. ("He said,'she's cute' and then smile at her."). You need to escape it:

"He said,'she\'s cute' and then smile at her."

Strings and arrays are treated as object. As as such, they have properties and methods. In fact, a string can be thought of a an array of characters so that  you can use the .length property to ascertain the length of a string.

[Back to Top]

Working with Date Object

The date object will return both the date and time. For example,

var today = new Date() will return the date and time.

You can also pass in year, month, day and/or second

var myBirthDate (1961, 11, 13) //Month is zero-based; hence Dec is 11

console.log ("I was born: ", myBirthDate)

The date is stored as the number of ms since Jan. 1 1970

Date methods:

today.getMonth //return 0-12

today.getFullYear //return full year

today.getYear //depreciated

tody.getDate //return 1-31

today.getDay //return 0-6

today.getHour //return 0-23

today.getTime // return ms since 1/1/70 The getTime method is helpful to determine differences between dates.

var dateA = new Date(1961,11,1)

var dateB = new Date(1961,11,1)

if (dateA == dateB) {code} //return false because the two dates are objects

if(dateA.getTime() == dataB.getTime() {code} // will return true

There are also some set functions:

today.setMonth

today.setFullYear

tody.getDate

[Back to Top]

JavaScript Objects

You can create objects in JavaScript but not like other programming language. JavaScript does not have the concept of classes. JS has some built in object (Date, Array, etc.)

Objects are a CONTAINER that encapsulates variables and functions.

You could use a series or variables that defines an object like this

var name = "Cornelius"

var city = "Round Rock"

var state = "Texas"

However, an object will encapulate these varables in a nice container

First, you have to create the container to "house" those variables. They are called properties INSIDE of an object and variables OUTSIDE an object.

var Student= new Object

Student.name = "Cornelius"

Student.city = "Round Rock"

Student.state = "Texas"

You can also create an object using an associative array:

var Student = {name:"Cornelius", city:"Round Rock", State:"Texas:"}

To create a method for an object you have to associate it with that object:

First create a function that will be called by the object

function getStudentInfo{

//Student1.name

console.log (this.name + "live in " + this.city + " " + this.state + ".")

//this keyword is used so that the object that is being called is replaced with the word this.,

}

Student1.getInfo = setStudentInfo //Associate object with function here

You still need to invoke the method of the object.

Student1.getInfo() // Notice the parenthesis

[Back to Top]

DOM Scripting

Document is the page, Object is an element, component (i.e., <p> tag) on a page, Model is how a page is represented (modeled) in a tree structure-like format and how the elements are related. Elements are represented by nodes that can be called by JavaScript to perform a certain task.

There are 12 nodes types; however, the top three are the most important ones:

Node.ELEMENT_NODE == 1
Node.ATTRIBUTE_NODE == 2
Node.TEXT_NODE == 3

If you examine the following code, you see these three nodes represented.

<ul id="nav">
    <li>Home</li>
    <li>Product</li>
    <li>Services</li>
    <li>Contact Us</li>
</ul>

The <ul> and <li> tags are element nodes. The "id="nav"" represent an attribute node and the text inside each of the <li> tags represent text nodes. Typically, the element node is target first to traverse the DOM tree.

If you need to target a SINGLE element on a page that has a UNIQUE id (i.e., id="nav"), you can target it with the following syntax:

document.getElementById("idName");

For example, to target the "nav" id of the bullet list code above, you can use the following code:

document.getElementById("nav");

Now, if you set this to a VARIABLE, you can create a HANDLE or a path to the element to read its properties or methods or use the variable as a "starting point" to traverse up or down the DOM tree for that page:

var menu = document.getElementById("nav"); //Not ...getElementByID -- notice ID instead of Id

If you need to target MULTIPLE elements on a page, you can target it with the following syntax:

document.getElementsByTagName("elementName"); //Notice the "s" on Elements 

For example, to target the <li> tag of the bullet list, you can write the following code:

document.getElementsByTagName("li");

Children elements (<li>) creates an ARRAY of its parent tag (<ol> or <ul>). As a result, you can create a HANDLE to multiple elements on a page. This is like a CSS tag selector, it will Target every TAG of That Type Totally (T5).  In our example, every <li> tags.

var menuItems = document.getElementsByTagName("li");

This will return an array that will hold an index for each <li> tag on the page regardless where it is or who its parent is. (i.e., menuItem[0], menuItem[1], menuItem[2]).

NOTE: If you target an element that does not exist, it will return a blank array of that array name.

Now you can ascertain certain properties of the element that is targeted:

console.log("Element type: " , menuItems.nodeType);
console.log("Element text: " , menuItems.innerHTML);
console.log("Element children: " menuItems.childNodes.length); //childNodes in itself is an array so  you can get its length.
console.log("Number of menu items: " , menuItems.length);

Now to get the best of both worlds, what if you wanted to target only the <li> tag in the navbar area of the page and not the bullet list on the page. This is similar to a contextual selector in CSS where you target a tag within a tag.

You can use a two fold approach, first, target the main tag using the the document.getElementById as a variable. And then, use that variable to target only the element within that tag.

var menuList = document.getElementById("nav");
var menuList.getElementByTagName("li");

This will target only the <li> tag in the <ul> tag that has an Id of "nav." Notice the second statement is NOT using "document." instead it uses "menuList" because the document reference is inside the "menuList" array.

[Back to Top]

Changing DOM Elements

Now that you have an understanding what DOM is, you can now use it to MODIFY or ADD styles or properties of an element (tag). You first need to target an element, then you get to its children, text or attributes to make changes.

To set or get an attribute, you can use the following syntax:

targetElement.getAttribute("attributeName", "value") or targetElement.setAttribute("attributeName", "value")

For example, to change the bullet list type from round bullet to square bullets, you could write the following code.

var menuList = document.getElementById("nav");
menuList.setAttribute("listStyleType", "square")

While not as easy to read, you could also combine the two lines together like this:

var menuList = document.getElementById("nav").setAttribute("listStyleType", "square")

IMPORTANT NOTE: Notice the CSS attribute name was changed from list-style-type to listStyleType because you can not use minu sign (-) in programming code because JavaScript would think you want to subtract items. It is important to remember that if the attribute does not exist, it will be created.

If you need to read or change a content of an element that has simple text in it (i.e, <p>, <a>, or <h1>), you can use the innerHTML method. For example, to change the content of the first bullet in our list, we could write the following code:

menuList.innerHTML = "The menu item has been change by JavaScript"

However, if you have a parent tag (i.e., <div> tag, <ul>tag) with other children elements in it, you will get all of the HTML elments.

For example, if you type the following code, you get all of the <li> tag in the <ul> element

var menuList = document.getElementById("nav")
var ListBulletItems = menuList.innerHTML
console.log(ListBulletItems)

While you can use innerHTML to write tags into another tag, it is best practice to create complex text structure by creating new elements and then adding it to the right location in the document DOM.

First, create an element that is separate from the document DOM using the following syntax:

var newElement = document.createElement("elementName")

For example, if we want to add another bullet to our current bullet list, we could write the following code:

var newElement = document.createElement("li")

Next, you have to append the newly created elements to a place in the document's DOM by using the following syntax:

myElement.appendChild(elementName)

For example, we could now append it the the current bullet list using the following syntax:

nav.appendChild(newElement)

Thirdly, we need to add text to the element that have been appended. Since the text node is a separate element like the <li> tag in our example, it too has to be created and appended the the other element that was created (i.e, the recently created <li> tag that was appended to the bullet list).
NOTE: We could have used the innerHTML to add the text; however, using the appendChild is a better approach for a large amount of text.  

To create a text node for our example, you can use the following syntax

var myText = document.createTextNode("This is a new text added to the the newly created bullet.");

Now that the text node is created, we need to add it to the <li> tag.

newElement.appendChild(myText);

While appendChild is used to add an element to the end of an existing element, you can also use another technique to insert the element anywhere within an element. For example, if we wanted to add a <li> tag as the bullet list instead of the last, you could use the following syntax:

First, create the element as before

var myNewBulletItem = document.createElement("li");

But this time create a variable the will hold a reference to where you want to position the elemnet if it does not have an id. In our example, we want to position it at bullet two.

var secondBulletItem = nav.getElementById("li")[1];

Now insert it at position two:

nav.insertBefore(myNewButlletItem, secondBulletItem);

[Back to Top]

Event and EventListeners

When you write code without any eventlisteners, the code is execute when the page is load. To create code the is more interactive you will have to create events or eventlisteners.

Events are happening all the time (i.e., onload, click, etc.); however, you can choose which once you want to listen to. Built in event in JavaScript usually begin with the word "on." For example, the following are some common events that you can listen for: onclick, onload, onfocus , onblur, onmouseover.

To listen for an event, you set up a function called an event listener

You can set up an event in four different ways:

1. You can embed the event handler directly inside an elemnt. While this is the easy way to create an event, it is the least prefer method because you are tighly coupling HTML with the code which makes it harder to reuse. To write an event listener to do something when a button is clicked, you could use the following code:

<button onclick = "alert('This is a test');">Click to open dialog box</button>
NOTE: Multiple statements could be added by separating them with semicolon.

2. Another way is to write a function in the <head> and make a call to it from another object (i.e., button).

<script>
function myFunction{
   alert('This is a test')
};
</script>

<button onclick = "myFunction()">Click to open dialog box</button>

3. The third way to write an event using the object dot syntax that uses an anynomous function.

object.event

For example, to write an event above using this technique, you could use the following syntax:

myButton.onclick = function() {
alert("This is a test");
};

NOTE: Notice the semicolon at the end of this statement (not function). The statement is calling a function when an event is called (in this case, a click event). Unlike a regular function that needs to be called or invoked outside of the function, this anynomous function is "called" when an event happens and as such there is no need for a function name.

4. There fourth way to write an event is to use an addEventListener (similiar to Flash), using the following syntax that listen for an event and then run a function when the event happens.

element.addEventListener('eventName', eventHandler, boolean)

Example:

myButton.addEventListener('click', buttonHandler, false)

function buttonHandler()
{
alert("This is a test");
}
NOTE: Notice the event is without the word "on": click instead of onclick.
NOTE: You also have an removeEventListener to remove the event once it is not needed anymore.

IMPORTANT NOTE: Internet Explorer prior to IE9 does not have and addEventListener method but has a similar method called attachEvent (i.e., document.attachEvent('onclick',myFunction)). So it is best to use the third method unless you know the user has IE9 or higher using some type of detection:

function CrossBrowserEventListener (elementName, eventName, functionName){
if(elementName.addEventListener){
elementName.addEventListener(eventNamae, functionName, false);
return true;
}
else {
elementName.attachEvent("on" + eventName, fucntionName);
return true;
}
}


A better approach instead of writing your own cross browser code is to use a third party class library like jQuery.

The following code uses the onblur and onfocus to ensure the user enter information in the email field that as an id of email and a default value of "enter your email."

var user_email = document.getElementByID("email")
emailField.onfocus = function() {
if(user_email.value == "enter your email"){
user_email.value = "";
}
user_email.onblur = function(){
if(user_email.value == ""){
user_email.value = "enter your email";
}



NOTE: Notice we are checking for the value property and NOT the innerHTML. The value property is used for most form elements.

[Back to Top]

Timer Methods

There are two timers methods setTimeout and setInterval

The setTimeout method used the following syntax and runs only ONCE.

setTimeout(functionToRun, delayInMilliseconds)

For example to have the alert box show after 6 seconds, you can write the following code:

setTimeout(openAlertBox, 6000)

function openAlertBox()
{
    alert("This window opened after a 6 seconds delay)
}

Unlike the setTimeout method that only execute a function once, the setInterval will execute a function REPEATILY. The syntax is basically the same.

setInterval(functionToRunRepeatily, howOftenToRunFunction)

For example, to create a simply slideshow you could write the following code

var imageGallery = document.getElementById("imageContainer");

var imageGalleryArray = ["roses.jpg", "daisy.jpg", "sunflower.jpg", "bird_of_paradise"];
var imageIndex = 0;

function updateImage()
{
imageGallery.setAttribute("src", imageGalleryArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageGalleryArray.length)
{
imageIndex = 0;
}
//run timer
setInterval(updateImage, 6000):

There are two other timer methods that are used to CLEAR the timer, namely, clearTimeout and clearsetInterval.
For example, to stop the photo gallery, you can write the following code:



In order to get a reference the the time method, change it  to refer to a variable (i.e., intervalHandeler),  then write the following additional code below it.

var intervalHandler = setInterval(updateImage, 6000);
imageContainer.onclick = function()
{
clearInterval(intervalHandler);
};

[Back to Top]

Working with Forms

Form elements have some unique properties and methods associated with them unlike other elements on a page.

Form elements fall into three major categories:

TIP: You can remember them by using the acronym SIT.
Below is a classical example that prevents the form from submitting
<script>
function  formEventHandler()
{
document.getElementById(“contactForm”).onsubmit = function()
{  if(document.getElementById(“email”).value == “”)
{
document.getElementById(“errorMessage”).innerHTML = “Please enter an email address.”
//Don’t submit form
return false;
}
else
{
//reset form
document.getElementByID(“errorMessage”).innHTML = “”;
return  true;
}
}
}
window.onload = function()
{
formEventHandler();
}
</script>
….
<p><span id=”errorMessage”></span></p> //This is in the body of the page with nothing in it.
….
Another classic example when using a form is the ability to hide/show elements that are not needed until a user makes a selection. For example, you could write a form that hide the field for checkboxes of the days a potential employee can work:
function showHideContent() {
document.getElementById("selectDays").onclick = function() {
if (document.getElementById("selectDays").checked) {
document.getElementById("daysAvaliable").style.display = "block";
}
else {
document.getElementById("daysAvaliable").style.display = "none";
}
};
//Hide on page load
document.getElementById("daysAvaliable").style.display = "none";
}
window.onload = function() {
showHideContent();
};

IMPORTANT NOTE: Notice that the “if” statement is not assigned a value. The reason for this is that the checked property itself is a Boolean. The block value of the display property will allow the content to be shown; whereas, the “none” value of the display property will hide the content.
You can use the following syntax to get to the form or elements in a form if it has an id or name property:

document.forms.nameOfForm //Get name of form
document.forms.nameOfForm.formElementName //Get name of element in form
However, using document.getElementById is still a better, easier and more consistent approach.
Notice that the document.getElementById(“xxxxx”).style.display = “none”  is listed twice in the code. The first time is in the “if” statement and the second time outside of the “if” statement so that it can be initial shown if the user does not have JavaScript turned on.  If they do have JavaScript turned on, then hide it upfront from the user.  This is an essential part of programming with progressive enhancement.

[Back to Top]

Styling Elements with JavaScript

You should always use CSS whenever possible.  However, when you need to DYNAMIC style an element of a page you can use JavaScript to do so
You can style elements with JavaScript in a similar manner that you style elements with CSS. The syntax is:
element.style.style_property
For example, to change the color of a paragraph to blue that has an id of “warning”, can be styled by writing the following line of code:
Warning.style.color = “blue”;
Other examples:
Warning.style.left = “30px”;
Warning.style.backgroundColor = “red”;
IMPORTANT NOTE: While you have the same properties in CSS, some of them are written differently if they have multiple words in them separated by dash. So they have to be written in camel Case instead. The reason for this is that if you use a dash JS would interpret this as a subtract symbol instead and variables and functions (properties and methods) cannot have dashes in them.

While the previous example is akin to an inline style added to an element, if you want to apply an existing class to an element using JavaScript, you could do this as well that is akin to an internal or external class rule.  Unlike CSS where you use the word “class” do define a class in an element (i.e., (<p class=”warning”>This is a Warning…</p>), you have to use the “className” property instead.
You need to set the class property using “.className” and not “.class”
Element.className = “classRealName”;
To clear a clear (set it back to the page default values) set it equal to a blank string: Element.className = “”;
A classic example of applying a class from a CSS file is to toggle a property on or off:
First write the CSS class that you will want to use:
.myNewClass {color: red; font-size:14px;}
Then, write some code to manipulate this class:
function manipulateCSS() {
document.getElementById("myText").onclick = function()
{             
if (document.getElementById("myText").className == "myClass") {
document.getElementById("myText").className = "";
}
else {
document.getElementById("myText").className = "myClass";
}
};
}
window.onload = function() {
manipulateCSS();
};

While you can apply a class in code it is still using the CSS rules.  So if there are other CSS rules that trump the current CSS rule it will do so. (i.e., the style closest to the source will trump any other rule.)

[Back to Top]

Animating Objects

To animate an object using JavaScript, you use the setInterval method to create the animation.
In this example, an object is taken out of HTML using absolute positioning to POSITION it and then after a delay allow to MOVE across the stage:
var currentPos = 0;
var intervalHandler;
//Move object to starting position
function beginAnimation() {
document.getElementById(“myTextBox”).style.position  = “absolute”;
document.getElementById(“myTextBox”).style.left  = “0px”;
document.getElementById(“myTextBox”).style.top  = “100px”;
//call animateObject function 50 times/sec
intervalHandler = setInterval(animateBox, 50);
}
function animateBox() {
//animate object 5 pixels for each iteration
currentPos+=5;
document.getElementById(“myTextBox”).style.left  = currentPos + “px”;
if (currentPos >900) {
//reset object properties to default
document.getElementById(“myTextBox”).style.position  = “”;
document.getElementById(“myTextBox”).style.left  = “”;
document.getElementById(“myTextBox”).style.top  = “”;
}
}
window.onload = function() {
//Run function after 5 sec
setTimeout (beginAnimation, 5000);
}

[Back to Top]

JavaScript (and Flash) Best Practices

There are a host of JavaScript libraries that you can use.  Below are some more popular ones.  A JavaScript library is useful for cross-browser detections when working with events (addEventListener for example is not supported in IE), animation, traversing the DOM, updating pages, etc.  You can download any of these libraries from the following web sites.  Most of the libraries are open source (free).  jQuery is the MOST popular JavaScript library.

There are also general purpose JavaScript library the serve a particular function:

It is important to remember that you want to limit the number of JavaScript libraries that you are using because each one has to make a request to the server in the order in which they are listed.  For example, if you are going to use jQuery on your page, it is important to load jQuery FIRST before you load jQueryMobile because jQueryMobile relies on jQuery.

[Back to Top]

JavaScript with HTML5


myObject.addEventListener(mouseEvent:mouseEvent: myMouseEvent, false)

function myMouseEVent() {
//code goes here…
}

In JavaScript, the function is INSIDE the addEventListerner as an anonymous (no name) function:
myObject.addEventListener (“mouse”, function() { //add code here}, false);

[Back to Top]

JavaScript and HTML5 Video

<video id=”myVideo” controls preload=”auto”>
<source src=”myVideoFile.mp4” type = “video/mp4” />
<source src=”myVideoFile.webm” type = “video/webm” />
<source src=”myVideoFile.ogv” type = “video/webm” />
< -- If video is not supported then write this message to screen. -->
<p> Your browser does not support HTML5 video. </p>
</video>

You have all of the new methods (i.e., .play(), .pause(), etc.)

.play();
.pause();
.currentTime = 0;

myVideo.addEventListener(“ended”, function() { // code to run when video is finished}, false);

HTML5 Storage
HTML5 and JavaScript also allow you to store (set) and retrieve (get) values as well as offline storage that do not require a network connection that is called WebSQL or IndexedDB:
localStorage[“username”] = name;
var name = localStroage[“username”]

[Back to Top]

Web Workers

There is a new feature call Web Workers that allows you to load JavaScript and make it run in the background (multithreading).

var worker = new Worker(“anotherjavascriptfile.js”);
//get ready to receive message from the worker
worker.onmessage = function(e) {
console.log(“The worker called me!);
};
//send messages to the worker
worker.postMessage(“firstFunction”);

[Back to Top]

Feature Detection

When implementing new features, you don’t won’t to ask “does this browser support this feature?” because we are not interested in BROWSER DETECTION, we are interested in FEATURE DETECTION. Instead we ask the question, does the current browser (regardless of what browser) support THIS new HTML5 feature and if so what to do if it does and what to do if it DOES NOT.  To do this, you treat the feature as an object and determine if it exists. For example, if you want to determine if the new getElementByClassName exist, you could write the following code. If it exists, it will return true:
if(document.getElementsByClassName){
//does feature exist, do this….
}else {
//it does not exist, do something else
}
You can do this with any of the new features in HTML5.

[Back to Top]

Using Modernizr

You can use a third party application called Modernizer to detect new HTML5 and CSS3 features.  (http://www.modernizr.com/) Download the code and place it in the head of your document because this code needs to run immediately before the <body> tag loads.  Once it runs, you will have a new JavaScript object called Modernizr.  Then you can check for over 40 features (i.e., Modernizr.video) If you run this object on different browser you will get different results.
If (Modernizr.video) {
// Yes, it support HTML5 video, then use it
}else {
//use a Flash video
}

Like jQueryMobile, you can customize the feature that you need so the JavaScript file would be smaller and load faster. For example, if you know you don’t need audio and video than you can exclude those features from the custom JavaScript download.
Modernizr does not give you the features you need only detect if they exist or not.  However, it can help you load in shim or polyfill to load in some alternative code to emulate the features you want.


Strict mode is part of EMCScript 5. Strict mode allows you to execute code at a higher (stricter) standard.  To implement strict mode, you add a line at the top of the JavaScript code like this in quote: “use strict”; or as the first line of a function if you want to do it one function at a time.  However, only certain browser support strict mode syntax; however, they will ignore it as a string literal. Browser will be hold your code to a higher standard.  If you don’t define a variable, the browser will throw an error.

[Back to Top]

Creating Objects in JavaScript

Until now we have seen how to use built-in objects in JavaScript (i.e., var  todayDate = new Date(); var myArray = new Array()).  JavaScript uses the prototype model to create objects (Not to be confused with the Prototype class library).
You can create an object like this:
var studentName  { name:”Cornelius”,grade:A :
name:”Mary”,  grade:B,
name:”Bob”; grade:B }

[Back to Top]

Handling Errors

You have to turn on the error handling capabilities of a browser in order to view errors. However, it is best to use third party app to capture error. Firebug is the most popular  tool to use to work with errors.

[Back to Top]

Misc.

Resource:

Aptana - (http://aptana.com) a free open source IDE for working with HTML, CSS, JavaScript, PHP and Ruby on Rails.
Eclipse - (http://www.eclipse.org) a free open source IDE for working with HTML, CSS, JavaScript
HTML Validator plug-in-- http://users.skynet.be/mqueury/mozilla Used to validate a page directly in a web browser. (Link not working)
Safari Validator -- http://zappatic.net/projects/safarivalidator/ Validate website for (x)html compliance.

[Back to Top]

JavaScript Errors - Try , Catch and Throw

The try statement lets you to test a block of code for errors.

The catch statement lets you handle the error.

The throw statement lets you create custom errors (exceptions).

MEMORY TIP: Try is used to "try" the code, catch is used to "catch" error, and throw is used to "throw" expections or meaningful errors.

When code is executed, different errors can occur and are typically displayed and the program will stop execution

  1. Syntax errors made by developer
  2. Misspelled  words
  3. Wrong user inputs, etc.

 

Try and Catch

The try statement allows a code block to be tested for errors while it is being executed.

The catch statement define a code block to be executed, if an error occurs in the try block.

These statements come in pairs (try and catch).

Syntax

try
{
//Run some code here
}
catch(error)
{
//Handle errors here
}

Examples

In the example below, we have deliberately made a typo in the code in the try block.

The catch block catches the error in the try block, and executes code to handle it:

Example

<!DOCTYPE html>
<html>
<head>
<script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(error)
{
errorMessage ="There was an error on this page.\n\n";
errorMessage+="Error description: " + error.message + "\n\n";
errorMessage+="Click OK to continue.\n\n";
alert(errorMessage);
}
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()">
</body>

</html>

The Throw Statement

The throw statement allows you to create a custom error.

The correct technical term is to create or throw an exception.

If you use the throw statement together with try and catch, you can control program flow and generate custom error messages.

Syntax

throw exception

The exception can be a JavaScript String, a Number, a Boolean or an Object.

Example

This example examines the value of an input variable. If the value is wrong, an exception (error) is thrown. The error is caught by the catch statement and a custom error message is displayed:

Example

<script>
function myFunction()
{
try
{
var x=document.getElementById("demo").value;
if(x=="")    throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10)     throw "to high";
if(x<5)      throw "too low";
}
catch(err)
{
var y=document.getElementById("mess");
y.innerHTML="Error: " + err + ".";
}
}
</script>

<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>

onError

<!DOCTYPE html>

<html>

<head>

<script>

onerror=handleErr;

var txt="";

function handleErr(msg,url,l)

{

txt="There was an error on this page.\n\n";

txt+="Error: " + msg + "\n";

txt+="URL: " + url + "\n";

txt+="Line: " + l + "\n\n";

txt+="Click OK to continue.\n\n";

alert(txt);

return true;

}

function message()

{

adddlert("Welcome guest!"); //Typo add purposely....

}

</script>

</head>

<body>

<input type="button" value="View message" onclick="message()" />

</body>

</html>